import React, { useState, useEffect } from 'react';
import { StyleSheet, Text, View } from 'react-native';
import { Camera, CameraProps } from 'expo-camera';

interface CameraVideoProps extends CameraProps {}

export default function CameraVideo(props: CameraVideoProps) {
  const [hasPermission, setHasPermission] = useState<null | boolean>(null);

  useEffect(() => {
    (async () => {
      const { status } = await Camera.requestPermissionsAsync();
      setHasPermission(status === 'granted');
    })();
  }, []);

  if (hasPermission === null) {
    return <View style={[styles.camera, props.style]} />;
  }
  if (!hasPermission) {
    return (
      <View style={[styles.permissionDenied, props.style]}>
        <Text style={styles.permissionDeniedText}>无法访问摄像头</Text>
      </View>
    );
  }

  return (
    <Camera
      style={[styles.camera, props.style]}
      type={Camera.Constants.Type.front}
      {...props}
    />
  );
}

const styles = StyleSheet.create({
  camera: {
    backgroundColor: '#555555',
  },
  permissionDenied: {
    flex: 1,
    justifyContent: 'center',
    alignItems: 'center',
    backgroundColor: '#555555',
  },
  permissionDeniedText: {
    color: '#ffffff',
  },
});
